package com.jdd.enterprise.exception;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.jdd.enterprise.api.vo.ApiResponse;
import com.jdd.enterprise.util.BasicRespCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.List;
/**
 * @Brief 全局异常处理
 * @Author cyl
 * @Date 2019年9月23日
 * @Version 1.0.0
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {
    /**
     * dto参数验证异常处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ApiResponse<String> bindExceptionHandler(BindException e) {
        ApiResponse<String> response = ApiResponse.fail(BasicRespCode.FAIL.desc);
        if (ObjectUtils.isNotEmpty(e)) {
            List<ObjectError> errList = e.getAllErrors();
            StringBuilder errStr = new StringBuilder();
            errList.forEach(err -> errStr.append(err.getDefaultMessage()).append(","));
            response.setMsg(errStr.deleteCharAt(errStr.length() - 1).toString());
        }
        return response;
    }
    /**
     * 数据注入异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public ApiResponse<String> methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        ApiResponse<String> response = ApiResponse.fail(BasicRespCode.FAIL.desc);
        if (ObjectUtils.isNotEmpty(e)) {
            response.setMsg("参数的数据类型异常");
        }
        return response;
    }
    /**
     * MySql语法异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BadSqlGrammarException.class)
    public ApiResponse<String> badSqlGrammarException(BadSqlGrammarException e) {
        ApiResponse<String> response = ApiResponse.fail(BasicRespCode.FAIL.desc);
        if (ObjectUtils.isNotEmpty(e)) {
            response.setMsg("语法异常");
        }
        return response;
    }
    /**
     * MySql语法异常
     *
     * @param
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = FailException.class)
    public ApiResponse<String> failException(FailException e) {
        return ApiResponse.fail(e.getMsg());
    }
}
